package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.product.vo.CategoryEntityVo;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationServiceImpl categoryBrandRelationService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 功能描述：
     *
     * @Author: zhangziyang
     * @Date: 10:35 2022/9/27
     * @return:递归获取所有菜单及其子菜单 TODO:此方法效率不高可以参考下面根据分组获取子菜单
     **/
    @Override
    public List<CategoryEntityVo> listWithtree() {
        List<CategoryEntity> entities = this.list();
        List<CategoryEntityVo> collectVo = entities.stream().map(item -> {
            CategoryEntityVo categoryEntityVo = new CategoryEntityVo();
            BeanUtils.copyProperties(item, categoryEntityVo);
            return categoryEntityVo;
        }).collect(Collectors.toList());

        List<CategoryEntityVo> treeMenu = collectVo.stream().filter(item -> item.getParentCid() == 0).map(item -> {
                    item.setChildren(getChilrens(item, collectVo));
                    return item;
                }
        ).sorted((p, n) -> (p.getSort() == null ? 0 : p.getSort()) - (n.getSort() == null ? 0 : n.getSort())).collect(Collectors.toList());

        return treeMenu;
    }


    private List<CategoryEntityVo> getChilrens(CategoryEntityVo vo, List<CategoryEntityVo> collectVo) {

        List<CategoryEntityVo> collect = collectVo.stream().filter(item -> {
            return item.getParentCid() == vo.getCatId();
        }).map(item -> {
            item.setChildren(getChilrens(item, collectVo));
            return item;
        }).sorted((p, n) -> (p.getSort() == null ? 0 : p.getSort()) - (n.getSort() == null ? 0 : n.getSort())).collect(Collectors.toList());
        return collect;
    }

    /**
     * 功能描述：
     *
     * @Author: zhangziyang
     * @Date: 10:35 2022/9/27
     * @return: 通过分组获取所有菜单及其子菜单
     **/
    @Override
    public List<CategoryEntityVo> listWithtreeByGroup() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntityVo> collect = list.stream().map(item -> {
            CategoryEntityVo categoryEntityVo = new CategoryEntityVo();
            BeanUtils.copyProperties(item, categoryEntityVo);
            return categoryEntityVo;
        }).collect(Collectors.toList());
        Map<Long, List<CategoryEntityVo>> collectMap = collect.stream().filter(item -> item.getParentCid() != 0).collect(Collectors.groupingBy(item -> item.getParentCid()));
        collect.stream().forEach(item -> item.setChildren(collectMap.get(item.getCatId())));
        return collect.stream().filter(item -> item.getParentCid() == 0).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前菜单是否被其他地方引用
        this.removeByIds(asList);
    }


    /**
     * 功能描述：
     *
     * @Author: zhangziyang
     * @Date: 14:51 2022/10/25
     * @return: 查找菜单全路径
     **/
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        //不建议调用递归
        //findParentPath(catelogId, paths);
        findParentPathByWhile(catelogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }


    //TODO 不建议递归查询全路径
    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);

        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }

    }

    //TODO 循环查询全路径
    private void findParentPathByWhile(Long catelogId, List<Long> paths) {
        while (catelogId != 0) {
            paths.add(catelogId);
            CategoryEntity category = this.getById(catelogId);
            catelogId = category.getParentCid();
        }
    }

    //级联更新所有关联数据
    @CacheEvict(value = {"category"},key = "'getLevel1Categorys'")
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        String name = category.getName();
        Long catId = category.getCatId();
        categoryBrandRelationService.updateCategory(catId, name);
    }

    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys.....");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间："+ (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {


        /**
         * 1.空结果缓存：解决缓存穿透
         * 2.设置过期时间（加随机值）:解决缓存雪崩
         * 3.加锁：解决缓存击穿
         */

        //1.查缓存
        String catelogJSON = stringRedisTemplate.opsForValue().get("CatelogJSON");

        if (StringUtils.isBlank(catelogJSON)) {
            //2.没有就查数据库
            System.out.println("缓存不命中，将要查询数据库");
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();

            return catalogJsonFromDB;
        }
        System.out.println("缓存命中直接返回");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, Map.class);

        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {


        synchronized (this) {
            //得到锁以后 去缓存中确定一次，如果有数据就不需要走库了
            String catelogJSON = stringRedisTemplate.opsForValue().get("CatelogJSON");
            if (StringUtils.isNotBlank(catelogJSON)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJSON, Map.class);
                return result;
            }

            System.out.println(Thread.currentThread().getId()+"查询了数据库...........");

            //将数据库的多次查询变为一次
            List<CategoryEntity> selectList = this.baseMapper.selectList(null);

            //1、查出所有分类
            //1、1）查出所有一级分类
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

            //封装数据
            Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //1、每一个的一级分类,查到这个一级分类的二级分类
                List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

                //2、封装上面的结果
                List<Catelog2Vo> catelog2Vos = null;
                if (categoryEntities != null) {
                    catelog2Vos = categoryEntities.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                        //1、找当前二级分类的三级分类封装成vo
                        List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                        if (level3Catelog != null) {
                            List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                                //2、封装成指定格式
                                Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                return category3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(category3Vos);
                        }

                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }

                return catelog2Vos;
            }));

            //3.转JSON字符串后放缓存
            String s = JSON.toJSONString(parentCid);
            stringRedisTemplate.opsForValue().set("CatelogJSON", s, 1, TimeUnit.DAYS);
            return parentCid;

        }
    }


    /**
     * 缓存里的数据如何和数据库的数据保持一致？？
     * 缓存数据一致性
     * 1)、双写模式
     * 2)、失效模式
     * @return
     */

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        //1、占分布式锁。去redis占坑
        //（锁的粒度，越细越快:具体缓存的是某个数据，11号商品） product-11-lock
        //RLock catalogJsonLock = redissonClient.getLock("catalogJson-lock");
        //创建读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");

        RLock rLock = readWriteLock.readLock();

        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            rLock.lock();
            //加锁成功...执行业务
            dataFromDb = getCatalogJsonFromDB();
        } finally {
            rLock.unlock();
        }
        //先去redis查询下保证当前的锁是自己的
        //获取值对比，对比成功删除=原子性 lua脚本解锁
        // String lockValue = stringRedisTemplate.opsForValue().get("lock");
        // if (uuid.equals(lockValue)) {
        //     //删除我自己的锁
        //     stringRedisTemplate.delete("lock");
        // }

        return dataFromDb;

    }

    /**
     * 从数据库查询并封装数据::分布式锁
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        //1、占分布式锁。去redis占坑      设置过期时间必须和加锁是同步的，保证原子性（避免死锁）
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功...");
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                //加锁成功...执行业务
                dataFromDb = getCatalogJsonFromDB();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

                //删除锁
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }
            //先去redis查询下保证当前的锁是自己的
            //获取值对比，对比成功删除=原子性 lua脚本解锁
            // String lockValue = stringRedisTemplate.opsForValue().get("lock");
            // if (uuid.equals(lockValue)) {
            //     //删除我自己的锁
            //     stringRedisTemplate.delete("lock");
            // }

            return dataFromDb;
        } else {
            System.out.println("获取分布式锁失败...等待重试...");
            //加锁失败...重试机制
            //休眠一百毫秒
            try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
            return getCatalogJsonFromDbWithRedisLock();     //自旋的方式
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }
}
